package NetWork;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class MyUDPServer {
    //创建socket，用于发送和接收数据报
    private DatagramSocket socket;
    //构造方法（指定端口号）
    public MyUDPServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    //启动服务器和内部逻辑
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            //1，创建数据报用来接收接收客户端的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //socket接收
            socket.receive(requestPacket);
            //为了方便处理接收到的信息将其转化为字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2，服务器根据请求计算响应
            String response  = process(request);
            //再将响应转换为数据报
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes(StandardCharsets.UTF_8).length,
                    requestPacket.getSocketAddress());
            //3，将响应发回客户端
            socket.send(responsePacket);
            //日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }
    //服务器根据请求计算响应
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        MyUDPServer myUDPServer = new MyUDPServer(6666);
        myUDPServer.start();
    }
}
